package mm.card.service;


import mm.card.pojo.MyUserDetails;
import mm.card.pojo.SystemUser;
import mm.card.pojo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Created by Yif on 2016/10/17.
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    /*@Resource(name = "UserRoleServiceImpl")*/
    @Autowired
    private UserRoleService userRoleService;

   /* @Resource(name = "SystemUserServiceImpl")*/
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SystemUser user;
        try {
            user = systemUserService.findByName(userName);
        }catch (Exception  e){
            throw new RuntimeException();
        }
        if(user == null){
            throw new UsernameNotFoundException("no user found");
        } else {
            try {
                List<UserRole> roles = userRoleService.getRoleByUser(user);
                return new MyUserDetails(user, roles);
            } catch (Exception e) {
                throw new UsernameNotFoundException("user role select fail");
            }
        }
    }
}
